package handler

import (
	"fmt"
	"io"
	"myApp/service"
	"net/http"
	"os"
	"path/filepath"
	"unicode/utf8"

	"github.com/gin-gonic/gin"
)

func Get(c *gin.Context) {
	getReq := &service.GetServiceRequest{}
	if err := c.ShouldBindJSON(getReq); err != nil {
		c.JSON(400, gin.H{"error": err})
		return
	}
	if (getReq.CustId == nil && getReq.Mobile == nil) ||
		(getReq.CustId != nil && utf8.RuneCountInString(*getReq.CustId) > 20) ||
		(getReq.Mobile != nil && utf8.RuneCountInString(*getReq.Mobile) > 20) {
		c.JSON(400, gin.H{"error": "Invalid Params"})
		return
	}
	// 查询数据库
	getResp, err := service.GetService(getReq)
	if err != nil {
		c.JSON(400, gin.H{"error": err})
		return
	}
	c.JSON(200, getResp)
}

func Export(c *gin.Context) {
	expReq := &service.ExportServiceRequest{}
	err := c.ShouldBindJSON(expReq)
	if err != nil {
		c.JSON(400, gin.H{"error": err})
		return
	}
	// 参数校验
	if (expReq.ProvFilterType == nil && expReq.Province != nil) ||
		(expReq.ProvFilterType != nil && expReq.Province == nil) ||
		(expReq.ProvFilterType != nil && (*expReq.ProvFilterType != "include" && *expReq.ProvFilterType != "exclude")) {
		c.JSON(400, gin.H{"error": "Invalid Params"})
		return
	}

	expResp, err := service.ExportService(expReq)
	if err != nil {
		c.JSON(400, gin.H{"error": err})
		return
	}
	c.JSON(200, expResp)
}

func Download(c *gin.Context) {
	filePath := c.Query("file")
	if filePath == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "File parameter is missing"})
		return
	}

	// 打开文件
	file, err := os.Open(filePath)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
		return
	}
	defer file.Close()

	// 设置响应头
	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filepath.Base(filePath)))
	c.Header("Content-Type", "application/zip")

	// 将文件内容写入响应
	_, err = io.Copy(c.Writer, file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to send file"})
	}
}
